//
//  ZWTabBarController.swift
//  SwiftFreshBeen
//
//  Created by Apple on 16/12/22.
//  Copyright © 2016年 zhouwnegang. All rights reserved.
//

import UIKit

class ZWTabBarController: UITabBarController {
    
    var tabTabItemTag:NSInteger = 0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //添加子控制器
        addChildControllers()
        
    }
    
    
    private  func addChildControllers() {
        //v2_home_25x25_
        addChildController(title: "首页", vc: ZWHomeViewController(), imageName: "v2_home")
        //v2_order_25x25_
        addChildController(title: "快闪购物", vc: ZWOrderViewController(), imageName: "v2_order")
        //shopCart_25x25_
        addChildController(title: "购物车", vc: ZWShopCarViewController(), imageName: "shopCart")
        //v2_my_r_25x25_
        addChildController(title: "我的", vc: ZWMyViewController(), imageName: "v2_my")
        
    }
    
    
    private func addChildController(title:String , vc:UIViewController, imageName:(String)){
        
        vc.title = title
        
        let normalImage:String = String(format: "%@_25x25_", imageName)
        vc.tabBarItem.image = UIImage(named: normalImage)?.withRenderingMode(.alwaysOriginal)
        
        let selectedImage:String = String(format: "%@_r_25x25_", imageName)
        vc.tabBarItem.selectedImage = UIImage(named:selectedImage)?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.darkGray], for: .normal)
        
        //创建导航控制器
        let navVc:(ZWNavController) = ZWNavController(rootViewController: vc)
        
        self.addChildViewController(navVc)
        
        //设置tag值
        vc.tabBarItem.tag = tabTabItemTag
        self.tabTabItemTag = self.tabTabItemTag+1
        
    }
    
    //设置tabBar的点击动画
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        
        var index = 0
        
        for subView in tabBar.subviews {
            
            if subView .isKind(of: NSClassFromString("UITabBarButton")!) {
                
                if index == item.tag {
                    
                    for v in subView.subviews {
                        if v.isKind(of: NSClassFromString("UIImageView")!) {
                            
                            v.transform = CGAffineTransform.init(scaleX: 0.6, y: 0.6)
                            UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 6, options: [], animations: {
                                v.transform = CGAffineTransform.identity
                            }, completion: { (_) in
                                print("👌")
                            })
                        }
                    }
                    
                }
                
                index += 1
            }
            
        }
        
    }
    
}


